﻿using UnityEngine;
using System.Collections;

public class followArrowScript : MonoBehaviour {
	
	Transform myChild;
	public Transform partnerRend;
	public playerScript playerData;
	DataScript data;
	
	// Use this for initialization
	void Start () {
		data = GameObject.FindGameObjectWithTag("DataManager").GetComponent<DataScript>();
		myChild = transform.GetChild(0);
		Debug.Log(data.partnerID);
		myChild.renderer.material.mainTexture = (GameObject.FindGameObjectWithTag("AssetManager").GetComponent<AssetManagerScript>().playerHeadTex[data.partnerID] as Texture2D);
		this.renderer.enabled = false;
		myChild.renderer.enabled = false;
	}
	
	float tmpCount = 0;
	// Update is called once per frame
	void Update () {
		if(partnerRend != null)
		{
			//Debug.Log(partnerRend.renderer.isVisible);
			if(!partnerRend.renderer.isVisible && playerData.isAlive)
			{
				if(!this.renderer.enabled)
				{
					this.myChild.renderer.enabled = true;
					this.renderer.enabled = true;
				}
				
				myChild.transform.rotation = Quaternion.identity;
				transform.position = partnerRend.position;
				
				Vector3 tmpPos = transform.localPosition;
				tmpPos.x = Mathf.Clamp(tmpPos.x,-11,11);
				tmpPos.y = Mathf.Clamp(tmpPos.y,-5.5f,5.5f);
				tmpPos.z = 5;
				transform.localPosition = tmpPos;
				
				Vector3 tmpVec2 = partnerRend.transform.position - transform.position;
				Vector2 tmpVec = new Vector2(tmpVec2.x,tmpVec2.y);
				tmpVec.Normalize();
				
				float YoffSetRot = Mathf.Rad2Deg * Mathf.Asin(tmpVec.y);
				//Debug.Log(YoffSetRot);
				
				Vector3 tmpRot = transform.eulerAngles;
				tmpRot.z = (Mathf.Rad2Deg * Mathf.Asin(tmpVec.x));// + YoffSetRot > 0 ? 0 : 180;
				if(YoffSetRot > 0)
				{
					if(tmpRot.z > 0)
						tmpRot.z += YoffSetRot * 2;
					else
						tmpRot.z -= YoffSetRot * 2;
				}
				transform.eulerAngles = tmpRot;
				
			}
			else
			{
				if(this.renderer.enabled)
				{
					this.myChild.renderer.enabled = false;
					this.renderer.enabled = false;
				}
			}
		}
		
	}
	
	public void setPlayer(playerScript data)
	{
		playerData = data;
		partnerRend = data.myRendeder.transform;
	}
}
